package vip.liux.front.application.clients;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import feign.RequestInterceptor;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import vip.liux.application.dots.ListResultDto;
import vip.liux.users.UserData;

import java.time.Duration;
import java.util.UUID;

@FeignClient(
        name = "user-lookup-app-service",
        url = "https://internal.liux.vip",
        configuration = UserLookupAppServiceClient.UserLookupAppServiceClientConfiguration.class
)
public interface UserLookupAppServiceClient {
    Cache<String, HttpClientExternalUserLookupServiceProvider.TokenModel> TOKEN_CACHE = Caffeine
            .newBuilder().initialCapacity(1).maximumSize(100L)
            .expireAfterWrite(Duration.ofHours(7L))
            .build();

    @GetMapping("/api/identity/users/lookup/{id}")
    UserData<UUID> findById(@PathVariable String id);

    @GetMapping("/api/identity/users/lookup/username/{username}")
    UserData<UUID> findByUsername(@PathVariable String username);

    @GetMapping("/api/identity/users/lookup/search/count")
    long count(@SpringQueryMap UserLookupSearchInputDto input);

    @GetMapping("/api/identity/users/lookup/search")
    ListResultDto<UserData<UUID>> search(@SpringQueryMap UserLookupSearchInputDto input);

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class UserLookupSearchInputDto {

        public String sorting;

        public String filter;

        public long maxResultCount;

        public long skipCount;

        public UserLookupSearchInputDto(String filter) {
            this.filter = filter;
        }
    }

    class UserLookupAppServiceClientConfiguration {

        @Bean
        public RequestInterceptor requestInterceptor() {
            return requestTemplate -> {
                HttpClientExternalUserLookupServiceProvider.TokenModel token = TOKEN_CACHE.getIfPresent("token");
                if (token != null) {
                    requestTemplate.header("Authorization", "Bearer " + token.getAccess_token());
                }
            };
        }
    }
}
